<template>
  <!-- 捐赠者信息网格布局容器 -->
  <div class="donor-grid">
    <!-- 循环渲染捐赠者卡片列表 -->
    <div
      v-for="(item, index) in userList"
      :key="item.donorId"
      class="donor-card"
    >
      <!-- 1️⃣ 可点击的图片：懒加载 + 小手 -->
      <a
        class="donor-image-link"
        href="javascript:void(0)"
        @click="goToDetail(item)"
      >
        <img
          class="donor-image__img"
          v-lazy
          :data-src="item.photoUrl.split(',')[0] || deflutImage"
          alt="donor photo"
        />
      </a>

      <!-- 2️⃣ 卡片头部：徽章 & 媒体数量（懒加载） -->
      <div class="card-header">
        <div class="header-left">
          <span class="donor-id">{{ item.donorId }}</span>
          <!-- 收藏icon -->
          <img
            v-if="isFavorited(item)"
            v-lazy
            class="badge-icon"
            data-src="/img/5hhxAppTchkA.png"
            alt="frozen donation badge"
            @click="cancleClick(item, index)"
          />
          <img
            v-else
            v-lazy
            class="badge-icon"
            data-src="/img/ps9dtwpgbaua7m66ivh0f27hwfa63eyj6iiff8c5823.png"
            alt="badge icon"
            @click="saveClick(item, index)"
          />
        </div>

        <div class="header-right">
          <span class="media-count">{{ item.photoNum }}</span>
          <img
            v-lazy
            class="media-icon"
            data-src="/img/psqzcr9q0kjugojilzr7idrcmlydf7dxjfb85477e7.png"
            alt="photo icon"
          />
          <span class="media-count">{{ item.videoNum }}</span>
          <img
            v-lazy
            class="media-icon"
            data-src="/img/psdbnghkpwnbg38ld11t5wbyq2tnajwarun1c00ad19.png"
            alt="video icon"
          />
        </div>
      </div>

      <!-- 3️⃣ 分隔线 -->
      <div class="divider"></div>

      <!-- 4️⃣ 当前状态 -->
      <div
        class="status-text"
        :class="{
          'status-active': item.status,
          'status-inactive': !item.status,
        }"
      >
        目前状态：{{ item.status }}
      </div>

      <!-- 5️⃣ 详细信息表格 -->
      <div class="card-details">
        <div class="details-grid">
          <div class="detail-row">
            <div class="detail-label">年龄</div>
            <div class="detail-value">{{ item.ageAtDonation }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">身高</div>
            <div class="detail-value">{{ Math.floor(item.height) }}cm</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">体重</div>
            <div class="detail-value">{{ Math.floor(item.weight) }}kg</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">血型</div>
            <div class="detail-value">{{ item.bloodType }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">眼睛颜色</div>
            <div class="detail-value">{{ item.eyeColor }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">头发颜色</div>
            <div class="detail-value">{{ item.hairColor }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">肤色</div>
            <div class="detail-value">{{ item.skinTone }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">最高学历</div>
            <div class="detail-value">{{ item.educationLevel }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">种族</div>
            <div class="detail-value">{{ item.ethnicity }}</div>
          </div>
          <div class="detail-row triple-column">
            <div class="detail-label">开放身份捐献还是匿名？</div>
            <div class="detail-value">
              {{ item.anonymous ? "匿名" : "开放身份" }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 6️⃣ 分页组件 -->
  <div class="pagination-container">
    <el-pagination
      :current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[9, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import deflutImage from "/no.png";
import { deleteFavorites, insertFavorites } from "@/api/business/parents-to-be";

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const rouPageNum = ref(1);
const rouPageSize = ref(9);

/* ---------------- 0. 新增：分页计算属性 ---------------- */
const emit = defineEmits([
  "update:pageNum",
  "update:pageSize",
  "handleSizeChange",
  "handleCurrentChange",
]);
const props = defineProps({
  userList: { type: Array, required: true },
  total: { type: Number, required: true },
  pageNum: { type: Number, required: true },
  pageSize: { type: Number, required: true },
});

/* 计算属性：双向绑定分页，同时同步到地址栏 query */
const currentPage = computed({
  get: () => props.pageNum,
  set: (val) => {
    emit("update:pageNum", val);
    emit("handleCurrentChange", val);
  },
});
const pageSizeSync = computed({
  get: () => props.pageSize,
  set: (val) => {
    emit("update:pageSize", val);
    emit("handleSizeChange", val);
  },
});

/* 进入页面时，如果地址栏自带 query 就同步一次（防止 F5 刷新丢失） */
onMounted(() => {
  const qn = route.query.pageNum;
  const qs = route.query.pageSize;
  if (qn) emit("handleCurrentChange", parseInt(qn));
  if (qs) emit("handleSizeChange", parseInt(qs));
});

/* 6 同步地址栏 */
const syncQuery = () => {
  router.replace({
    name: route.name,
    query: {
      ...route.query,
      pageNum: rouPageNum.value,
      pageSize: rouPageSize.value,
    },
  });
};

/* ---------------- 1. 原有逻辑保持不变 ---------------- */
const saveFlag = ref(false);

/* 懒加载指令 */
const vLazy = {
  mounted(el) {
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src || "";
            io.unobserve(img);
          }
        });
      },
      { threshold: 0.1 }
    );
    io.observe(el);
  },
};

/* 跳转详情 */
const goToDetail = (item) => {
  router.push({
    path: "/parents/detail",
    query: {
      id: item.donorId,
      userId: item.userId,
      pageNum: props.pageNum,
      pageSize: props.pageSize,
    },
  });
};

/* 分页大小 / 页码 触发（现在只做 emit，不写 query） */
const handleSizeChange = (val) => {
  rouPageSize.value = val;
  pageSizeSync.value = val;
  syncQuery();
};
const handleCurrentChange = (val) => {
  rouPageNum.value = val;
  currentPage.value = val;
  syncQuery();
};

/* 收藏相关 */
const isFavorited = (item) => {
  if (!item.favorites) return false;
  return item.favorites.split(",").includes(userStore.id + "");
};
const saveClick = (item) => {
  if (saveFlag.value) return ElMessage.error("请不要连续点击");
  saveFlag.value = true;
  insertFavorites({
    userId: userStore.id,
    donorId: item.donorId,
    type: "egg",
  }).then(() => {
    ElMessage.success("收藏成功");
    saveFlag.value = false;
    const set = new Set(item.favorites ? item.favorites.split(",") : []);
    set.add(userStore.id + "");
    item.favorites = Array.from(set).join(",");
  });
};
const cancleClick = (item) => {
  if (saveFlag.value) return ElMessage.error("请不要连续点击");
  saveFlag.value = true;
  deleteFavorites({
    userId: userStore.id,
    donorId: item.donorId,
    type: "egg",
  }).then(() => {
    ElMessage.success("取消成功");
    saveFlag.value = false;
    const set = new Set(item.favorites ? item.favorites.split(",") : []);
    set.delete(userStore.id + "");
    item.favorites = Array.from(set).join(",");
  });
};
</script>

<style scoped lang="scss">
/* 默认字体与颜色 */
$font-default: "Microsoft YaHei", "微软雅黑", sans-serif;
$color-default: #333;

/* 样式保持不变，仅做最小必要调整 */
.donor-grid {
  margin-top: 10px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  font-family: $font-default;
  color: $color-default;

  @media (min-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
  @media (min-width: 1024px) {
    grid-template-columns: repeat(3, 1fr);
  }
}

.donor-card {
  border: 1px solid #a2c4e8;
  border-radius: 8px;
  padding: 20px;
  cursor: default; // 卡片除图片外默认箭头
  font-family: $font-default;
  color: $color-default;

  /* ========== 图片区域 ========== */
  .donor-image-link {
    // display: block;
    cursor: pointer;
  }

  /* 原文件 scoped 里改这一处即可 */
  /* ===== 图片区域 ===== */
  .donor-image-link {
    display: block;
    width: 100%; /* 让父级有宽度，aspect-ratio 才能生效 */
    height: auto !important;
  }

  /* 深度选中：绕过 scoped 哈希 & 权重问题 */
  :deep(.donor-image__img) {
    aspect-ratio: 3 / 4 !important; /* 锁死 321:459 */
    object-fit: cover !important; /* 不想裁就改成 contain */
    width: 100%;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px 0;
    font-family: $font-default;
    color: $color-default;

    .header-left,
    .header-right {
      display: flex;
      align-items: center;
      gap: 15px;
    }
    .donor-id {
      font-size: 24px;
    }
    .badge-icon {
      height: 24px;
    }
    .media-count {
      font-size: 16px;
      color: #4d4d4d;
    }
    .media-icon {
      width: 22px;
      height: 22px;
    }
  }

  .divider {
    background-color: #e6e6e6;
    height: 1px;
  }

  .status-text {
    margin-top: 20px;
    text-align: center;
    font-size: 16px;
    font-family: $font-default;

    &.status-active {
      color: #2b5cab;
    }
    &.status-inactive {
      color: #4d4d4d;
    }
  }

  .card-details {
    margin-top: 38px;
    font-family: $font-default;
    color: $color-default;

    .detail-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      padding: 8px 0;
      border-bottom: 1px solid #e0e0e0;

      &.triple-column {
        grid-template-columns: 2fr 1fr;
      }

      .detail-label {
        font-size: 16px;
        color: #4d4d4d;
        line-height: 24px;
        font-family: $font-default;
      }

      .detail-value {
        font-size: 16px;
        color: #2b5cab;
        text-align: right;
        line-height: 24px;
        font-family: $font-default;
      }
    }
  }
}

.pagination-container {
  width: 60%;
  padding: 40px 0;
  margin: 0 auto;
  font-family: $font-default;
  color: $color-default;
}
</style>
